import React, { useState, useCallback } from "react";
import debounce from "lodash/debounce";



export default function DebounceDemo() {
    const [value, setValue] = useState<string>('');
    const [duration, setDuration] = useState<number>(2);

    const addX = () => {
        console.log(value);
        setValue(value + "x");
    }

    const addY = useCallback(() => {
        setValue((prev) => {
            console.log(Date.now(), prev);
            return prev + "y"
        });
    }, []);

    // duration改变时，重新生成一个debounce函数，更新防抖动时间
    // eslint-disable-next-line
    const debounceAddY = useCallback(debounce(addY, duration * 100), [duration]);
    
    // 这种写法在调用 dounceAddY，并不会执行 addY方法，因为useCallback只是返回了 debounce(addY, 300)的执行结果，它返回了一个函数，但不会执行;
    // const dounceAddY = useCallback(() => {
    //     console.log('useCallback before return dounceAddY');
    //     return debounce(addY, 300);
    // }, []);

    const increaseTime = () => setDuration(duration + 1);
    const decreaseTime = () => setDuration(Math.max(duration - 1, 0));

    return (
        <div>
            <h1>DebounceDemo</h1>
            <button onClick={addX}>普通按钮X</button>
            <span>{value}</span>
            <button onClick={debounceAddY}>防抖动按钮Y</button>
            <span>
                （防抖间隔：
                <button onClick={decreaseTime}>-</button>
                {duration * 100}
                <button onClick={increaseTime}>+</button>
                毫秒）
            </span>
            <span>{value}</span>
            
        </div>
    );
}